
import { ref } from "vue";

const BASE_URL: string = 'http://47.119.167.251:1890'
export const WEB_SOCKET = 'http://47.119.167.251:1890/main/api/websocket'

// export const BASE_URL: string = 'http://192.168.137.1:1890';
// export const WEB_SOCKET = 'http://192.168.137.1:1890/main/api/websocket'


import type {RequestOptions} from "./RequestOptions";

export const request = (options: RequestOptions): Promise<any> => {

    console.log(options.method)
	console.log(options.data)
    // 判断是否需要token，并且token不存在时，直接拒绝Promise
    if (options.tokenRequired && !getToken()) {
        console.log("没有token")
        return Promise.reject('Token required');
    }

    return new Promise((resolve, reject) => {
        uni.request({
            url: BASE_URL + options.url,
            method: options.method,
            data: options.data,
            header: {
                'Authorization': `${getToken()}`, // 添加token到请求头
				'content-type': 'application/json'
            },
            success: (res) => {
                const data = res.data;
                console.log(data)
                if (data.code == 401) {
                    uni.navigateTo({
                        url: "/login"
                    });
                    reject('Unauthorized');
                } else if (data.code == 20001) {
                    console.log(data)
                    uni.showToast({
                        icon: 'none',
                        title: data.message
                    });
                    reject('Operation error');
                } else {
                    resolve(data);
                }
            },
            fail: (error) => {
                uni.showToast({
                    icon: 'none',
                    title: '系统错误'
                });
                reject(error);
            }
        });
    });
};

// 用于获取token的函数，您需要根据项目实际情况进行实现
function getToken(): string | null {
    return uni.getStorageSync('token');
}
